﻿using System;
using System.Net;
using System.Management;
using System.Text;

public class PC
{
    
    /// <summary>  
    /// 获取主机域名  
    /// </summary>  
    /// <returns></returns>  
    public static string GetPCName()
    {
        return Dns.GetHostName();
    }

    /// <summary>  
    /// 获取网卡的MAC地址  
    /// </summary>  
    /// <returns>返回一个string</returns>  
    public static string GetNetMAC()
    {
        string stringMAC = "";
        try
        {
            ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection MOC = MC.GetInstances();
            foreach (ManagementObject MO in MOC)
            {
                if ((bool)MO["IPEnabled"] == true)
                {
                    stringMAC += MO["MACAddress"].ToString();
                }
            }
            return stringMAC;
        }
        catch
        {
            return "";
        }
    }


    /// <summary>   
    /// 物理内存   
    /// </summary>   
    /// <returns></returns>   
    public static string GetTotalMemory()
    {
        string st = "";
        ManagementClass mc;
        ManagementObjectCollection moc;
        try
        {
            mc = new ManagementClass("Win32_ComputerSystem");
            moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                st = mo["TotalPhysicalMemory"].ToString();
            }
        }
        catch { return ""; }
        finally
        {
            moc = null;
            mc = null;
        }
        return st;
    }


    /// <summary>
    /// 使用BASE64加密的字符串,使用UTF8格式
    /// </summary>
    /// <param name="strText">加密前的字符串</param>
    /// <returns></returns>
    static string Base64str(string strText)
    {
        return Base64str(strText, System.Text.Encoding.GetEncoding("utf-8"));
    }
    /// <summary>
    /// 使用BASE64加密的字符串
    /// </summary>
    /// <param name="strText">加密前的字符串</param>
    /// <param name="ens">加密前的字符编码</param>
    /// <returns></returns>
    static string Base64str(string strText, System.Text.Encoding ens)
    {
        return Convert.ToBase64String(ens.GetBytes(strText));
    }

    public static string GetPCInfo()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("{");
        sb.Append("PC_Name:" + GetPCName() + ",");
        sb.Append("MAC:" + GetNetMAC().Replace(":", "#") + ",");
        sb.Append("Memory:" + GetTotalMemory() + ",");
        sb.Append("}");
        return Base64str(sb.ToString());
    }
}
